(function (d) {
	var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
	if (d.getElementById(id)) { return; }
	js = d.createElement('script'); js.id = id; js.async = true;
	js.src="js/facebook-lib.js";
	ref.parentNode.insertBefore(js, ref);
}(document));

function statusChangeCallback(response) {
	console.log('statusChangeCallBack');
	if (response.status === 'connected') {
		//Logged Facebook
		console.log("Đã đăng nhập");
		window.connectFacebook = true;
		/*FB.login(function(response) {
		}, {scope: 'publish_actions, user_photos, publish_stream', return_scopes: true});*/
	} else {
		window.connectFacebook = false;
		console.log("Facebook SDK: Not Connected");
	}
	//Đánh dấu là check xong facebook
	window.checkFacebook = true;
}
		
function checkLoginState() {
	FB.getLoginStatus(function(response) {
		statusChangeCallback(response);
	});
}
		
		
function getInformationFromFaceBook() {
	/*FB.api(
		"/me/albums",
		function (response) {
		console.log(response);
		  if (response && !response.error) {
			console.log(response);
		  }
		}
	); */

	/*FB.api('/me/albums', 'post',
		{
			name: 'Đuổi hình bắt chữ',
			message: 'Giải giúp mình với'
		},
		function(response) {
			console.log("album id: " + response.id);
		}
	);*/
	
	/*FB.api(
		"/me/feed",
		"POST",
		{
			"message": "This is a test message"
		},
		function (response) {
		  if (response && !response.error) {
		  }
		}
	);*/
	
	/*FB.api('/me/albums', 'post',
		{
			name: 'Đuổi hình bắt chữ',
			message: 'Giải giúp mình với'
		},
		function(response) {
			console.log("album id: " + response.id);
		}
	);*/

	FB.api('/me', function (me) {
		console.log(me);
		/*if (me.name) {
			console.log(me.name);
			document.getElementById('auth-displayname').innerHTML = me.name;
		}
		if (me.id) {
			document.getElementById('FBId').innerHTML = me.id;
			document.getElementById('Pic').src = 'https://graph.facebook.com/' + me.id + '/picture?type=normal';
			document.getElementById('Pic').alt = me.name;
			document.getElementById('Pic').title = me.name;
		}

		if (me.email) {
			document.getElementById("DisplayEmail").innerHTML = me.email;
		}
		if (me.gender) {
			document.getElementById("Gender").innerHTML = me.gender;
		}
		if (me.birthday) {
			document.getElementById("DOB").innerHTML = me.birthday;
		}
	*/
	});
	/*FB.logout(function(response) {
	  // user is now logged out
	});*/
}
 
var authToken; 
//Khi facebook load xong thì thực hiện
window.fbAsyncInit = function () {
	console.log("Kết nối xong facebook");
	 FB.init({
		appId: '1459687740983285', // App ID
		channelUrl: 'http://localhost:8000/batchu/', // Path to your   Channel File
		status: true, // check login status
		cookie: true, // enable cookies to allow the server to access the session
		xfbml: true  // parse XFBML
	});
	
	//Kiểm tra trạng thái hiện giờ có đang kết nối facebook hay ko
	checkLoginState();
	
	//Hàm kiểm tra nếu có sự thay đổi sẽ tự động load
	FB.Event.subscribe('auth.statusChange', function (response) {
	   if (response.authResponse) {
				init();
			window.authToken = response.authResponse.accessToken;
			FB.api('/me', function (me) {
				if (me.first_name) {
					if (!savescore) savescore = new SaveScore();
					savescore.setFirstName(me.first_name);
					console.log("first name: " + me.first_name);
				}
				if (me.last_name) {
					savescore.setLastName(me.last_name);
					console.log("last name: " + me.last_name);
				}
				if (me.id) {
					console.log("id : " + me.id);
					savescore.setFacebookId(me.id);
					savescore.setUrlPicture('https://graph.facebook.com/' + me.id + '/picture?type=normal');
					//Kiểm tra lên csdl
					savescore.getDataUser();
				}
			});
	   }
	});
}



function PostImageToFacebook(message, imageData) {
    try {
        blob = dataURItoBlob(imageData);
    } catch (e) {
        console.log(e);
    }
 //return;
    var fd = new FormData();
    fd.append("access_token", authToken);
    fd.append("source", blob);
    fd.append("message", message);
    try {
        $.ajax({
            url: "https://graph.facebook.com/me/photos?access_token=" + window.authToken,
            type: "POST",
            data: fd,
            processData: false,
            contentType: false,
            cache: false,
            success: function (data) {
                console.log("success " + data);
                $("#poster").html("Posted Canvas Successfully");
             	in_game.completePost();
            },
            error: function (shr, status, data) {
                console.log("error " + data + " Status " + shr.status);
                in_game.errorPost();
            },
            complete: function () {
                console.log("Posted to facebook");
            }
        });

    } catch (e) {
        console.log(e);
    }
}

// Convert a data URI to blob
function dataURItoBlob(dataURI) {
    var byteString = atob(dataURI.split(',')[1]);
    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ab], {
        type: 'image/png'
    });
}